package com.pap.rocketmq.service.impl;

import com.alibaba.fastjson.JSON;
import com.pap.rocketmq.config.RocketMQConfig;
import com.pap.rocketmq.entity.Mq;
import com.pap.rocketmq.service.IMqService;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Transactional
@Service("mqService")
public class MqServiceImpl implements IMqService {

    private static Logger logger = LoggerFactory.getLogger(MqServiceImpl.class);

    @Autowired
    private RocketMQConfig rocketMQConfig;

    @Resource(name = "mqTopicTransactionMQProducer")
    private TransactionMQProducer mqTopicTransactionMQProducer;

    public boolean create(Mq record) {
        try {
            Message mqMessage = new Message();
            mqMessage.setTopic(rocketMQConfig.getPapTopicMQTopic());
            mqMessage.setTags(rocketMQConfig.getPapTopicMQTopictag());
            mqMessage.setBody(JSON.toJSONBytes(record));
            TransactionSendResult transactionSendResult = null;
            transactionSendResult = mqTopicTransactionMQProducer.sendMessageInTransaction(mqMessage, null);

            return true;
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        return false;
    }

}